package com.qiudao.commonutil.util;

import org.apache.commons.configuration.CompositeConfiguration;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;

/**
 * Description: 属性工具类
 * 依赖 commons-configuration.commons-configuration
 * @author: gdc
 * @date: 2019/9/1
 * @version 1.0
 */
public class PropertyUtils {

    private static final Logger logger = LoggerFactory.getLogger(PropertyUtils.class);

    private PropertyUtils() {}

    public static Object getProperty(Object obj, String propertyName) {
        Object value = null;
        try {
            // 获取对象的类型
            Class clazz = obj.getClass();
            Method getMethod = clazz.getDeclaredMethod("get" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1));
            // 调用方法获取方法的返回值
            value = getMethod.invoke(obj);
        } catch (Exception ignored) {}

        return value;
    }

    /**
     * 获取messages.properties里的key对应的value值
     */
    public static Configuration getConfiguration() {
        CompositeConfiguration comp_config = new CompositeConfiguration();
        // 加载xml文件
        try {
            comp_config.addConfiguration(new PropertiesConfiguration("conf/config.properties"));
        } catch (ConfigurationException e) {
            logger.warn("读取配置文件出错！", e);
            logger.error(e.getMessage());
        }
        return comp_config;
    }
}
